<?php
/**
 * Product categories model. Describes categories products assigned to.  
 * 
 * @author Konstantin Shamko <konstantin.shamko@gmail.com> 
 * @version 0.0.1
 * @copyright  Copyright (c) 2009 Konstantin Shamko
 * @package Products Module
 * @license  New BSD License
 *
 */
class Models_Products_Categories extends Bel_Model_Abstract  {

	/**
	 * Array of many-to-one references with products  & categories.
	 * Realtion between products and categories is many-to-many
	 *
	 * @var array
	 */	
	protected $_referenceMap = array (
								'Product' => array (
									'columns' => 'product_id',
									'refTableClass' => 'Models_Products',
									'refColumns' => 'product_id', 
									'onDelete' => self::CASCADE	),
								'Category' => array(
									'columns' => 'category_id',
									'refTableClass' => 'Models_ProductCategories',
									'refColumns' => 'category_id', 
									'onDelete' => self::CASCADE	),
								);
	
     /**
     * Product ID. Used in _selectQuery method. Could be used
     * to store product id to be able to use it further in this class
     * methods
     *
     * @var integer
     */   								
	private $_product_id = null;								

	/**
	 * Constructor. Sets table name & primary key
	 *
	 * @return void
	 */
	public function __construct() {
		$this->_name = TABLE_PREFIX . "product2category";
		$this->_primary = array('product2category_id');
		parent::__construct ();
	}
	
	/**
	 * Set $_product_id
	 *
	 * @param integer $product_id
	 */	
	public function setProduct($product_id){
		$this->_product_id = $product_id;
	}

	/**
	 * Prepares select query for getAll() method to select  categories assigned to product.
	 * Product id is set via setProduct
	 *
	 * @return Zend_Db_Select
	 */	
	protected function _selectQuery(){
		$select = parent::_selectQuery();
		$oCategories = new Models_ProductCategories();
		$select->joinInner(array('c'=>$oCategories->info('name')),'c.category_id='.$this->_name.'.category_id');
		
		if($this->_product_id){
			$select->where('product_id=\''.$this->_product_id.'\'');
		}		
		return $select;
	}
}